<template>
  <div class="my-table" v-loading="tableLoading">
    <div class="table-search" v-if="hasSearch">
      <slot name="search"></slot>
    </div>
    <div class="table-action" v-if="hasAction">
      <slot name="tableAction"></slot>
    </div>
    <div class="table-body">
      <el-table :data="tableData" border style="width: 100%">
        <!-- label表示表头某一列具体名称 -->
        <!-- el-table-column用于定义表格的列 -->
        <el-table-column align="center" label="ID" width="80">
          <!-- 使用作用域插槽展示内容 -->
          <template v-slot="scope">
            {{ scope.$index + 1 + (pagination.pageNumber - 1) * pagination.pageSize }}
          </template>
        </el-table-column>
        <!-- 使用v-for循环，遍历propList数组渲染el-table-column -->
        <template v-for="propItem in propList" :key="propItem.prop">
          <el-table-column v-bind="propItem" align="center" show-overflow-tooltip>
            <template #default="scope">
              <!-- 使用具名插槽动态渲染内容 -->
              <slot :name="propItem.slotName" :row="scope.row">
                {{ scope.row[propItem.prop] }}
              </slot>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="table-pagination" v-if="hasPagination">
      <slot name="pagination">
        <!-- el-pagination用于分页功能 -->
        <el-pagination
          v-model:current-page="pagination.pageNumber"
          v-model:page-size="pagination.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </slot>
    </div>
  </div>
</template>

<script setup>
// 定义组件的props，包括isSearch、isAction等
defineOptions({ name: 'MyTable' })
defineProps({
  hasSearch: {
    type: Boolean,
    default: true
  },
  hasAction: {
    type: Boolean,
    default: true
  },
  hasPagination: {
    type: Boolean,
    default: true
  },
  tableLoading: {
    type: Boolean,
    default: false
  },
  tableData: {
    type: Array,
    required: true
  },
  propList: {
    type: Array,
    required: true
  }
})
const pagination = defineModel('pagination', {
  type: Object,
  default: () => ({ total: 0, pageSize: 10, pageNumber: 1 })
})

// 定义组件事件，包括update:pagination和updateBannerData
const emit = defineEmits(['updateBannerData'])

// 处理页码变化事件，更新pagination并触发updateBannerData事件
const handleCurrentChange = () => {
  emit('updateTableData')
}

// // 处理每页显示数量变化事件，更新pagination并触发updateBannerData事件
const handleSizeChange = () => {
  emit('updateTableData')
}
</script>

<style lang="scss" scoped>
.my-table {
  padding-top: 10px;
  .table-action {
    padding-right: 15px;
    display: flex;
    flex-direction: row-reverse;
    margin-bottom: 10px;
  }
  .table-search {
    margin-bottom: 10px;
  }
  .table-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
